const db=wx.cloud.database()
const pics = db.collection('pics')
const votes = db.collection('votes')
const $ = db.command.aggregate
Page({
  data:{
      maxvote:3,
  },
  async onLoad(option){
    
    let res= await pics.get()
    let plist = res.data

    res =await votes.get()
    let vlist = res.data

    plist.forEach(v=>{
      
      v.count=0
      vlist.forEach(vv=>{
        if(vv.fileid==v.fileid){
            v.count+=1
        }
      })
      if(v.count>=1){
        v.t=true
      }else{
        v.t=false
      }
      
    })
     res = await wx.cloud.callFunction({
      name:'login'
    })
    
    console.log('login:',res)
    let openid = res.result.openid
    let voted = false
    let votesum=0
    let today = new Date()
    today = today.toJSON().slice(0,10)
    console.log(today)
    vlist.forEach(v=>{
      if(v._openid==openid&&v.date.toJSON().slice(0,10)==today){
        votesum += 1
      }
    })
    let sheng=this.data.maxvote-votesum
    
    this.setData({
      plist,vlist
    })
    this.setData({
      votesum,sheng
    })
    if(option.fileid){
        let current = plist.findIndex(v=>{
          return v.fileid==option.fileid
        })
        this.setTitleBar(current)
        this.setData({
          current
        })
    }else{
        this.setTitleBar(0)
    }
  },
  async long(){
    let res = await wx.chooseImage({
      count:1,
      
    })
    console.log(res)
    let filename =res.tempFilePaths[0]
    let purfilename = filename.split('/').slice(-1)[0]
    res = await wx.cloud.uploadFile({
      cloudPath:'images/'+purfilename,
      filePath:filename
    })
    let fileid=res.fileID
    res=await pics.add({
      data:{
        fileid
      }
    })
    if(res.errMsg.indexOf('ok')>-1){
      wx,wx.showToast({
        title: '图片插入成功'
      })
    }
    wx.reLaunch({
      url: '/pages/work15/index?fileid'+fileid,
    })
  },
  async tap(e){
    if(this.data.votesum>=3){
      wx.showToast({
        title: '已投票不能再投',
      })
      return
    }
    console.log(e)
    let fileid = e.currentTarget.dataset.id
    let res = await votes.add({
        data:{
          fileid,
          date:db.serverDate()
        }
    })
    console.log(res)
    if(res.errMsg.indexOf('ok')>-1){
       await wx.showToast({
        title: '还有'+this.data.sheng+'次投票次数',
      })
    }else{
        await wx.showToast({
        title: '投票失败',
      })
    }
    
    wx.reLaunch({
      url: '/pages/work15/index?fileid'+fileid,
    })
  },
  setTitleBar(current){
    wx.setNavigationBarTitle({
      title:current+1+'/'+this.data.plist.length+' '+this.data.plist[current].count+'票'
    })
  },
  change(e){
    console.log(e)
    this.setTitleBar(e.detail.current)
  }
  
})